package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Service
@Slf4j
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    String prefix;

    @Value("${file.oss.web-site}")
    String webSite;



    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //校验参数
        if (multipartFile==null||multipartFile.getSize()==0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的文件");
        }

        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        String originalFilename = multipartFile.getOriginalFilename();

        //判断上传文件格式是否正确 判断是否是jpg结尾

        //截取文件结尾

        String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));

        String uuid = UUID.randomUUID().toString().replace("-", "");

        String fileName=uuid+suffix;

        //上传文件

        try {
            //store 是oss 的全路径名，包名加 uuid+jpg
            String store = fileStorageService.store(prefix, fileName, multipartFile.getInputStream());
            WmMaterial wmMaterial = new WmMaterial();

            wmMaterial.setUserId(user.getId()); //当前登录的用户
            wmMaterial.setUrl(store);//上传url
            wmMaterial.setType((short) 0);
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setCreatedTime(new Date());

            //保存素材
            save(wmMaterial);


            //返回前台 文件地址
           wmMaterial.setUrl(webSite+store);

            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("上传文件失败==》 {}",e.getMessage());
            return  ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"上传文件失败");
        }

    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        dto.checkParam();

        //判断当前是否登录
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.lambdaQuery();

        WmUser user = WmThreadLocalUtils.getUser();

        if(dto.getIsCollection()!=null&&dto.getIsCollection()==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        if(user==null){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        wrapper.eq(WmMaterial::getUserId,user.getId());

        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        IPage<WmMaterial> page = new Page(dto.getPage(),dto.getSize());

        IPage result = page(page, wrapper);

        List<WmMaterial> records = result.getRecords();

        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }


        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), result.getTotal());

        pageResponseResult.setData(result.getRecords());

        return pageResponseResult;
    }


    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 删除素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {
        // 1 参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2 业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if(count > 0){
            throw new CustomException( AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        // 删除素材库
        removeById(id);
        // 删除图片OSS
        fileStorageService.delete(wmMaterial.getUrl());
        // 3 封装结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新状态
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,uid));
        return ResponseResult.okResult();
    }
}
